<template>
	<view class="main">
		<v-tabs v-if="!selectStatus" :scroll="false" activeColor="#FF6543" lineColor="#FF6543" v-model="current"
			:tabs="tabs" @change="changeTab"></v-tabs>
		<view v-if="current==0" class="flex align warp" style="flex-wrap: wrap;">
			<view class="img-div" v-for="(item,index) in list" :key="index">
				<image :src="item.url" @click="toPre(item.url)"></image>
				<view class="btn" @click="todel(item.id)" v-if="!selectStatus">
					<uni-icons type="clear" size="30" color="red"></uni-icons>
				</view>
				<view v-if="selectStatus">
					<view v-if="item.checked" class="btns btns2" @click="toSelect(item.url,index)">已选择</view>
					<view v-else class="btns" @click="toSelect(item.url,index)">选择</view>
				</view>
			</view>
		</view>
		<view v-if="current==1" class="flex align warp" style="flex-wrap: wrap;">
			<view v-for="(item,index) in list" :key="index" class="img-div">
				<video :src="item.url" controls></video>
				<view class="btn" @click="todel(item.id)" v-if="!selectStatus">
					<uni-icons type="clear" size="30" color="red"></uni-icons>
				</view>
				<view v-if="selectStatus">
					<view v-if="item.checked" class="btns btns2" @click="toSelect(item.url,index)">已选择</view>
					<view v-else class="btns" @click="toSelect(item.url,index)">选择</view>
				</view>
			</view>
		</view>
		<view v-if="current==2" class="flex align warp" style="flex-wrap: wrap;">
			<view v-for="(item,index) in list" :key="index" class="img-div"
				style="margin: 20rpx;border-radius: 20rpx;background: white;width: 100%;padding: 20rpx;">
				<audio :src="item.url" :name="item.title" controls style="width: 100%;"></audio>
				<view>
					<view class="btns" @click="todel(item.id)" v-if="!selectStatus">
						删除
					</view>
					<view v-if="selectStatus">
						<view v-if="item.checked" class="btns btns2" @click="toSelect(item.url,index)">已选择</view>
						<view v-else class="btns" @click="toSelect(item.url,index)">选择</view>
					</view>
				</view>

			</view>
		</view>
		<uni-load-more :status="status" v-if="!empty" :content-text="loadText"></uni-load-more>
		<xw-empty :isShow="empty" text="暂无数据" textColor="#777777"></xw-empty>
		<view v-if="type2==1">
			<view class="main-btn" @click="toSelectCom()" v-if="selectStatus">确定选择</view>
			<view class="main-btn" @click="toUrl()" v-else>上传{{current==0?'图片':current==1?'视频':'音频'}}</view>
		</view>

	</view>
</template>

<script>
	import {
		generalAttachment,
		aliossNotify
	} from '@/api/apiData.js';
	import {
		uploadOss
	} from '@/until/oss/oss.js'
	export default {
		data() {
			return {
				current: 0,
				tabs: ['图片素材', '视频素材', '音频素材'],
				type: 1,
				group_id: '',
				totalPage: 1,
				page: 0,
				offset: 15,
				list: [],
				scrollTop: 0,
				empty: false,
				loadText: {
					loadmore: '点击或上拉加载更多',
					loading: '努力加载中',
					nomore: '实在没有了'
				},
				status: 'loadmore',
				imgList: [],
				urlsArr: [],
				urlsArrN: [],
				selectStatus: false,
				type2: 1,
				type3: ''
			};
		},
		onLoad(option) {
			console.log(decodeURIComponent('%7B%22mimetype%22%3A%22image%22%7D'))
			if (option.type) {
				this.type = option.type
				this.current = option.type - 1
				this.selectStatus = true
			}
			if (option.type2) {
				this.type2 = option.type2
			}
			if (option.type3) {
				this.type3 = option.type3
			}
			this.getlist()

		},
		onShow() {
			// this.page = 0
			// this.list = []
			// this.getlist()
		},
		onPageScroll(e) {
			const that = this;
			that.scrollTop = e.scrollTop;
		},
		onReachBottom() {
			const that = this;
			that.getlist();
		},
		methods: {
			toSelect(url, index) {
				this.list[index].checked = !this.list[index].checked
				if (this.type2 == 2) {
					let list = this.list
					let arr2 = []
					list.forEach(item => {
						if (item.checked) {
							arr2.push({
								url: item.url,
								type: 'image'
							})
						}
					})
					uni.setStorageSync('image', arr2);
					uni.navigateBack()
				}
			},
			toSelectCom() {
				let arr = []
				if (this.current == 2) {
					if (this.type3 == 2) {
						let list = this.list
						list.forEach(item => {
							if (item.checked) {
								arr.push({
									url: item.url,
									type: 'audio'
								})
							}
						})
						uni.setStorageSync('audio2', arr);
					} else {
						let list = this.list
						list.forEach(item => {
							if (item.checked) {
								arr.push({
									url: item.url,
									type: 'audio'
								})
							}
						})
						uni.setStorageSync('audio', arr);
					}

				}
				if (this.current == 1 || this.current == 0) {
					let list = this.list
					list.forEach(item => {
						if (item.checked) {
							if (this.current == 0) {
								arr.push({
									url: item.url,
									type: 'image'
								})
							} else {
								arr.push({
									url: item.url,
									type: 'video'
								})
							}

						}
					})
					let imgVideoArr = uni.getStorageSync('imgVideoArr')
					if (imgVideoArr) {
						imgVideoArr = imgVideoArr.concat(arr)
					} else {
						imgVideoArr = arr
					}
					uni.setStorageSync('imgVideoArr', imgVideoArr)
				}
				// if (this.current == 0) {
				// 	let list = this.list
				// 	let arr2 = []
				// 	console.log(arr)
				// 	console.log(list)
				// 	list.forEach(item => {
				// 		if (item.checked) {
				// 			arr2.push({
				// 				url: item.url,
				// 				type: 'img'
				// 			})
				// 		}
				// 	})
				// 	uni.setStorageSync('img', arr);
				// }
				// if(this.current==2){
				// 	uni.setStorageSync('audio', arr);
				// }
				uni.navigateBack()
			},
			todel(id) {
				let that = this
				uni.showModal({
					title: "提示",
					content: "确定要删除吗？",
					showCancel: true,
					success: res => {
						if (res.confirm) {
							that.delCom(id)
						} else {

						}
					}

				})
			},
			delCom(id) {
				let obj = {
					action: 'del',
					ids: id
				}
				let that = this
				uni.request({
					url: 'https://jzxt.jiugezixun.cn/storeadmin/general/attachment/select?element_id=fachoose-video1',
					data: obj,
					method: 'POST',
					header: {
						'content-type': 'application/x-www-form-urlencoded',
						'X-Requested-With': 'XMLHttpRequest',
						'Cookie': uni.getStorageSync('cookies') // 从存储中读取cookies并设置到请求头
					},
					success: result => {
						if (result.data.code == 1) {
							uni.showToast({
								title: '删除成功'
							})
							setTimeout(() => {
								that.page = 0
								that.list = []
								that.getlist()
							}, 500);
						} else {
							uni.showToast({
								title: result.data.msg,
								icon: 'none'
							})
						}
					},
					fail: result => {
						uni.hideLoading();
					}
				})
				// const result = await companyMateriaDelete({
				// 	ids: id,
				// })
				// if (result.code == 1) {
				// 	uni.showToast({
				// 		title: result.msg
				// 	})
				// 	setTimeout(() => {
				// 		this.page = 0
				// 		this.list = []
				// 		this.getlist()
				// 	}, 500);
				// } else {
				// 	uni.showToast({
				// 		title: result.msg,
				// 		icon: 'error'
				// 	})
				// }
			},
			toUrl() {
				if (this.current == 0) { //上传图片
					this.toUploadImg()
				} else if (this.current == 1) { //上传视频
					this.toUploadVideo()
					// uni.navigateTo({
					// 	url: '/pages/manage/upload?type=' + this.current + '&id=' + this.group_id
					// })
				} else { //上传音频
					this.toUploadAudio()
				}

			},
			// 上传图片
			toUploadImg() {
				let that = this
				uni.showLoading({
					title: "loading",
					mask: true
				})
				uni.chooseMedia({
					count: 9,
					mediaType: ['image'],
					sizeType: ['original'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['camera', 'album'], //从相册选择
					success: (res) => {
						console.log(res)
						// OSS上传(得到在oss文件夹下照片路径)
						let fileArr = res.tempFiles
						let length = fileArr.length

						fileArr.forEach((item, index) => {
							that.toOss(item.tempFilePath, index, item.fileType, item.size, new Date()
								.getTime())
						})
					},
					fail() {
						uni.hideLoading()
					}
				})
			},
			// 上传视频
			toUploadVideo() {
				let that = this
				uni.showLoading({
					title: "loading",
					mask: true
				})
				uni.chooseMedia({
					count: 9,
					mediaType: ['video'],
					sizeType: ['original'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['camera', 'album'], //从相册选择
					success: (res) => {
						console.log(res)
						let fileArr = res.tempFiles
						let length = fileArr.length
						fileArr.forEach((item, index) => {
							that.toOss(item.tempFilePath, index, item.fileType, item.size, new Date()
								.getTime())
						})
					},
					fail() {
						uni.hideLoading()
					}
				})
			},
			// 上传音频
			toUploadAudio() {
				let that = this
				uni.chooseMessageFile({
					count: 1,
					extension: [".mp3"],
					success: (res) => {
						console.log("从聊天记录中获取文件", res);
						const {
							errMsg,
							tempFiles
						} = res;
						if (errMsg == "chooseMessageFile:ok" && tempFiles.length) {
							const {
								name,
								size,
								path
							} = tempFiles[0];
							console.log("临时文件", {
								size,
								path
							});
							if (name.slice(-4) != ".mp3") {
								return uni.showToast({
									icon: "none",
									title: "请上传mp3文件！",
									duration: 2000,
								});
							}
							that.toOss(path, 1, 'audio', size, name)
							// this.uploadFile(path);
						}
					},
				});
			},
			async toOss(item, index, fileType, size, name) {
				const time = uni.$u.timeFormat(new Date().getTime(), 'yyyymm/dd')
				let ossPath = await uploadOss({
					filePathFore: time + '/',
					filePath: item,
				})
				let url = 'https://hongchuquan.oss-cn-shanghai.aliyuncs.com/' + ossPath
				console.log(url)
				this.toComf(url, fileType, size, name)
			},
			async toComf(url, fileType, size, name) {
				uni.showLoading({
					title: "loading",
					mask: true
				})
				const result = await aliossNotify({
					url: url,
					name: name,
					size: size,
					type: fileType,
				})
				if (result.code == 1) {
					uni.hideLoading()
					uni.showToast({
						title: '上传成功'
					})
					setTimeout(() => {
						this.urlsArr = []
						this.urlsArrN = []
						this.page = 0
						this.list = []
						this.getlist()
					}, 500);
				} else {
					uni.hideLoading()
					uni.showToast({
						title: result.msg,
						icon: 'error'
					})
				}
			},
			toDownImg(url) {
				uni.showLoading({
					title: '下载中...',
				})
				uni.downloadFile({
					//视频信息的Url
					url: url,
					success: function(res) {
						// 只要服务器有响应数据，就会把响应内容写入文件并进入 success 回调，业务需要自行判断是否下载到了想要的内容
						if (res.statusCode === 200) {
							console.log(res.tempFilePath);
							uni.saveVideoToPhotosAlbum({
								filePath: res.tempFilePath,
								success: function(res) {
									console.log(res.errMsg)
									uni.hideLoading();
									uni.showToast({
										title: '下载成功'
									})
								}
							})
						}
					},
					fail() {
						uni.showToast({
							title: '下载失败',
							icon: 'error'
						})
						uni.hideLoading();
					}
				})

			},
			toDown(url) {
				uni.showLoading({
					title: '下载中...',
				})
				uni.downloadFile({
					//视频信息的Url
					url: url,
					success: function(res) {
						// 只要服务器有响应数据，就会把响应内容写入文件并进入 success 回调，业务需要自行判断是否下载到了想要的内容
						if (res.statusCode === 200) {
							console.log(res.tempFilePath);
							uni.saveVideoToPhotosAlbum({
								filePath: res.tempFilePath,
								success: function(res) {
									console.log(res.errMsg)
									uni.hideLoading();
									uni.showToast({
										title: '下载成功'
									})
								}
							})
						}
					},
					fail() {
						uni.showToast({
							title: '下载失败',
							icon: 'error'
						})
						uni.hideLoading();
					}
				})

			},
			toPre(i) {
				uni.previewImage({
					urls: [i],
					current: 0
				})
			},
			changeTab(e) {
				console.log(e)
				this.type = e + 1
				this.page = 0
				this.list = []
				this.getlist()
			},
			async getlist() {
				const that = this;
				const {
					totalPage,
					page,
					offset,
					list,
					group_id,
					type
				} = that;
				let filter = ""
				let mimetype = ''
				if (type == 1) {
					filter = JSON.stringify({
						"mimetype": "image"
					})
					mimetype = 'image'
				}
				if (type == 2) {
					filter = JSON.stringify({
						"mimetype": "video"
					})
					mimetype = 'video'
				}
				if (type == 3) {
					filter = JSON.stringify({
						"mimetype": "audio"
					})
					mimetype = 'audio'
				}
				let obj = {
					mimetype: mimetype,
					sort: 'id',
					order: 'desc',
					offset: page,
					limit: offset,
					filter: filter,
					op: JSON.stringify({
						"mimetype": "LIKE"
					}),
					_: new Date().getTime()
				};
				that.status = 'loading';
				if (totalPage > page) {
					let result = await generalAttachment(obj);
					that.page = page + 1;
					if (result.total == 0) {
						that.empty = true;
						that.status = 'nomore';
						return;
					}
					that.empty = false;
					setTimeout(() => {
						that.status = 'loadmore';
					}, 500);
					result.rows.forEach(item => {
						item.checked = false
					})
					that.list = list.concat(result.rows);
					that.totalPage = Math.ceil(result.total / offset);
				} else {
					setTimeout(() => {
						that.status = 'nomore';
					}, 500);
				}
			},
		}
	}
</script>

<style lang="scss" scoped>
	.main {
		padding-bottom: 80rpx;
	}

	.btns {
		background: #FF6543;
		width: 120rpx;
		text-align: center;
		line-height: 48rpx;
		border-radius: 12rpx;
		color: white;
		margin: 0 auto;
		font-size: 26rpx;
	}

	.btns2 {
		background: grey;
	}

	.img-div {
		width: 33.33%;
		text-align: center;
		margin-top: 20rpx;
		position: relative;

		image,
		video {
			width: 92%;
			height: 200rpx;
			object-fit: cover;
			background: white;
		}
	}

	.btn {
		position: absolute;
		right: 0;
		top: -20rpx;
	}

	.list {
		margin: 24rpx;
		border-radius: 12rpx;

		image {
			width: 150rpx;
			height: 150rpx;
		}





		.list-info {
			margin-left: 20rpx;
			width: 73%;

			.name {
				font-size: 32rpx;
				font-weight: bold;
			}

			.time {
				color: gray;
				font-size: 28rpx;
				margin-top: 20rpx;
			}
		}




		.video-div {
			margin-bottom: 20rpx;
			background: white;
			padding: 16rpx 24rpx;

			video {
				width: 100%;
				height: 250rpx;
				object-fit: fill;
			}

			.name {
				text-align: center;
				margin-bottom: 20rpx;
				font-weight: bold;
			}

			.btn {
				margin: 0 auto;
			}
		}
	}

	.main-btn {
		font-size: 34rpx;
		font-weight: bold;
		color: white;
		text-align: center;
		background: #FF6543;
		line-height: 108rpx;
		position: fixed;
		bottom: 0;
		left: 0;
		width: 100%;
	}
</style>